<?php


namespace app\api\service;

use think\Config;
class CashServiceJft
{
    //配置信息
    private $config;
    const iv = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
    //是否绑卡需要异步通知
    public $bcardneedotifiy;
    public function __construct()
    {
        if (Config::has('cashconfigjft')){
            $this->config = Config::get('cashconfigjft');
        }else{
            $config = Config::load(ROOT_PATH.'application/api/config.php');
            $this->config = $config['cashconfigjft'];
            Config::set('cashconfigjft',$this->config);
        }
        $this->bcardneedotifiy = 1;
    }
    /**
     * 测试
     */
    public function test(){
        print_r($this->config);
    }
    /**
     * 发送接口数据
     * @param string $url
     * @param array $params
     */
    private function send(string $url,array $params){
        $params['verCode'] = '1001';
        $map['orgCode'] = $this->config['appid'];
        $map['signData'] = $this->sign($params);
        $map['encryptData'] = $this->encrypt($params,'base64',$this->config['aes_key']);
        $response =  curl_post($url,$map);
        //解密
        $resJson = json_decode($response,true);
        $resData = $this->decrypt($resJson['encryptData']);
        $resDataJson = json_decode($resData,true);
        return $resDataJson;

        //验签
        $this->checkSign($resJson['signData'],$resDataJson,$this->config['md5_key']);
    }

    /**
     * 生成签名
     * @param $data
     * @return bool|string
     */
    private function sign($data) {
        $md5Key = $this->config['md5_key'];
        $ret = false;
        if(empty($data) || !$data) return false;
        $str = $this->_ascii($data);
        $str .= '&md5key=' . $md5Key;
        if(!empty($str)){
            $ret = strtoupper(utf8_encode(md5($str)));
        }
        return $ret;
    }

    /**
     * 自定义ascii排序
     */
    public function _ascii($params = array()) {
        if(!empty($params)){
            $p =  ksort($params,SORT_NATURAL | SORT_FLAG_CASE);
            if($p){
                $str = '';
                foreach ($params as $k=>$val){
                    if ($val != null)
                    {
                        $str .= $k .'=' . $val . '&';
                    }
                }
                $strs = rtrim($str, '&');
                return $strs;
            }
        }
        return false;
    }

    /**
     * 自定义arr2url排序
     */
    public function _arr2url($params = array()) {
        if(!empty($params)){
            $str = '';
            foreach ($params as $k=>$val){
                isset($val) && $str .= $k .'=' . urlencode($val) . '&';
            }
            $strs = rtrim($str, '&');
            return $strs;
        }
        return false;
    }

    //加密
    public function encrypt($data, $code = 'base64', $password)
    {
        $json = utf8_encode(json_encode($data, true));
        $ret = false;
        $encrypt = $this->pkcs5Pad($json, '16');
        if ($data) {
            $openssl =  openssl_encrypt($encrypt, 'AES-128-CBC', $password, OPENSSL_RAW_DATA, self::iv);
            $ret = $this->_encode($openssl, $code);
        }
        return $ret;
    }

    //pkcs5加密
    public function pkcs5Pad($text,$blocksize){
        $pad = $blocksize-(strlen($text)%$blocksize);
        $return = $text.str_repeat(chr($pad),$pad);
        return $return;
    }

    private function _encode($data, $code)
    {
        switch (strtolower($code)) {
            case 'base64':
                $data = base64_encode('' . $data);
                break;
            case 'hex':
                $data = bin2hex($data);
                break;
            case 'bin':
            default:
        }
        return $data;
    }

    //解密
    public function decrypt($str)
    {
        $password = $this->config['aes_key'];
        $str =  base64_decode($str);
        $data = openssl_decrypt($str, 'AES-128-CBC', $password, OPENSSL_RAW_DATA, self::iv);
        $ret = $this->pkcs5Unpad($data);
        return $ret;
    }

    //pcks5解密
    public function pkcs5Unpad($text) {
        // 经测试, 服务器没有使用padding
        return $text;
    }

    //公钥验签
    public function checkSign($signedData, $encryptData, $md5Key){
        $reSign = $this->sign($encryptData, $md5Key);
        if($reSign == $signedData){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 商户注册
     * @param array $data
     * @return mixed
     */
    public function register(array $data){

        $url = 'https://test_tran.verajft.com/fusionPosp/interface/memberReg';
//        $url = 'https://client-api.verajft.com/fusionPosp/interface/memberReg';
        //组织数据
        $param = [];
        //商户编号
        $param['merCode'] = $data['user_id'];
        //商户姓名	M
        $param['merName'] = $data['name'];
        //结算户名
        $param['accountName'] = $data['name'];
        //真实姓名
        $param['realName'] = $data['name'];
        //详细地址
        $param['merAddress'] = $data['detail'];
        //开户证件号 身份证号	M
        $param['idCard'] = $data['idno'];
        //银行卡号	M
        $param['accountNo'] = $data['acctid'];
        //银行卡绑定手机号	M
        $param['mobile'] = $data['mobile'];
        //银行卡绑定手机号	M
        $param['reservedMobile'] = $data['mobile'];
        //联行号
        $param['subBankCode'] = $data['bankcode'];
        //结算户类型
        $param['settleAccType'] = 2;
        //统一整理返回数据***
//        $res =  $this->send($url,$param);
//        $res_data['code'] = $res['resCode'] == '0000'?1:$res['resCode'];
//        $res_data['msg'] = $res['resMsg'];
//        $res_data['merchantno'] = isset($res['chMerCode'])?$res['chMerCode']:'';
        $res_data['code'] = 1;
        $res_data['msg'] = '注册成功';
        $res_data['merchantno'] = rand(1000000,9999999);
        return $res_data;
    }

    /**商户业务开通
     * @param array $data
     * @return mixed
     */
    public function opening(array $data){
        $url = 'https://test-tran.verajft.com/fusionPosp/interface/memberBus';
        //组织数据
        $param = [];
        //chMerCode  busCode  drawFee  tradeRate
        $param['chMerCode'] = $data['merchantno'] ;
        $param['busCode'] = 2001;
        $param['tradeRate'] = $data['rate'];
        $param['drawFee'] = $data['fee'];
        //$res1 =  $this->send($url,$param);
        $param['busCode'] = 5002;
        //$res2 =  $this->send($url,$param);
        //$res_data['code'] = ($res1['resCode'] == '0000')&&($res2['resCode'] == '0000')?1:0;
        //$res_data['msg'] = "收银台业务:".$res1['resMsg']."|代偿业务:".$res2['resMsg'];
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }


    /**
     * 修改费率
     */
    public function changeRate($data){
        $url = 'https://test-tran.verajft.com/fusionPosp/interface/rateModify';
        //组织数据
        $param = [];
        $param['chMerCode'] = $data['merchantno'];
        $param['drawFee'] = $data['fee'];
        $param['tradeRate'] = $data['rate']*0.01;
        //$param['T1FeeRate'] = $data[''];??
        $param['busCode'] = 2001;
        //$res = $this->send($url,$param);
//        $res_data['code'] = $res['resCode'] == '0000'?1:$res['resCode'];
//        $res_data['msg'] = $res['resMsg'];
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }

    /**
     * 获取商户余额
     */
    public function getbalance(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * 收款商户mcc查询
     */
    public function getmcc(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * 获取收款商户信息
     */
    public function getbussinessinfo(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * consumption 绑定结算银行卡接口
     */
    public function bindcards(array $data){
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;

    }

    /**
     * 绑卡同步/异步接口
     */
    public function  bind_notifiy(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * 修改结算银行卡
     * @param array $data
     * @return mixed
     */
    public function changeBcard(array $data){
        //先调用解绑
        if (!$this->unbindcards($data)){
            throw new \think\Exception("银行卡解绑失败 ", 0);
        }
        $url = 'https://test-tran.verajft.com/fusionPosp/interface/bankCardModify';
        //组织数据
        $param = [];
        $param['chMerCode'] = $data['merchantno'];
        $param['accountName'] = $data['name'];
        $param['accountNo'] = $data['acctid'];
        $param['reservedMobile'] = $data['mobile'];
        $param['subBankCode'] = $data['bankcode'];
        //结算户类型
        $param['settleAccType'] = 2;
        //统一整理返回数据***
        //$res = $this->send($url,$param);
//        $res_data['code'] = $res['resCode'] == '0000'?1:$res['resCode'];
//        $res_data['msg'] = $res['resMsg'];
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }
    /**
     *consumption 结算银行卡解绑接口
     */
    public function unbindcards(array $data){
        $url = '';
        //组织数据
        $param = [];
        //商户号
        $param['merchantNo'] = $data['merchantno'];
        //银行卡卡号
        $param['accNo'] = $data['old_accno'];
        //$res = $this->send($url,$param);
//        $res_data['code'] = $res['resCode'] == '0000'?true:false;
//        $res_data['msg'] = $res['resMsg'];
        //成功返回 true  失败返回 false
        return true;
    }

    /**
     * 结算银行卡绑卡查询接口
     */
    public function find_cards(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * 绑定消费信用卡
     * @param array $data
     * @return mixed
     */
    public function bindCcard(array $data){
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }

    /**
     * 解绑消费信用卡
     * @param array $data
     */
    public function unbindCcard(array $data){
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }
    /**
     *消费接口
     */
    public function pay(array $data){
        $url = '';
        //组织数据
        $param = [];
        $param['chMerCode'] = $data['merchantno'];
        $param['orderCode'] = $data['order_no'];
        $param['orderTime'] = time();
        $param['orderAmount'] = $data['totle_money'];
        $param['realName'] = $data['realname'];
        $param['idCard'] = $data['certno'];
        $param['accNo'] = $data['accno'];
        $param['mobile'] = $data['phoneno'];
        $param['cvv2'] = $data['cvv2'];
        $param['validity'] = $data['validity'];
        $param['deviceSN'] = '';//$data[''];//终端设备的唯一标识码 IMEI/MEID/SN/UDID
        $param['deviceType'] = 1;
        $param['deviceIP'] = $data['user_id'];//公网ip
        $param['deviceLocation'] = $data['deviceLocation'];//纬度/经度
        $param['callBackUrl'] = "http://www.cash.com/notifiyjft.php?act=pay_notifiy";
        $param['settleType'] = 0;
        $param['busCode'] = 2005;
        //$res = $this->send($url,$param);
//        $res_data['code'] = $res['resCode'] == '0000'?1:$res['resCode'];
//        $res_data['msg'] = $res['resMsg'];
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
    }

    /**
     * 消费异步通知接口
     */
    public function pay_notifiy(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

    /**
     * 提现接口
     */
    public function cash(){
        $url = '';
        //组织数据
        $param = [];
        $res_data['code'] = 1;
        $res_data['msg'] = 'ok';
        return $res_data;
        //return $this->send($url,$param);
    }

    /**
     * 订单查询接口
     */
    public function find_orders(){
        $url = '';
        //组织数据
        $param = [];
        return $this->send($url,$param);
    }

}